package com.aqielife.aqiemusic.view;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.app.usage.NetworkStats;
import android.app.usage.NetworkStatsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.NetworkCapabilities;
import android.os.Build;
import android.os.Bundle;
import android.os.Process;
import android.os.RemoteException;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Choreographer;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.asynclayoutinflater.view.AsyncLayoutInflater;
import androidx.core.view.LayoutInflaterCompat;

import com.aqielife.aqiemusic.R;
import com.aqielife.aqiemusic.performance.adapter.OnFeedShowCallBack;
import com.aqielife.aqiemusic.performance.async.ThreadPoolUtils;
import com.aqielife.aqiemusic.performance.launchstarter.DelayInitDispatcher;
import com.aqielife.aqiemusic.performance.tasks.delayinittask.DelayInitTaskA;
import com.aqielife.aqiemusic.performance.tasks.delayinittask.DelayInitTaskB;
import com.aqielife.aqiemusic.performance.utils.LogUtils;
import com.zhangyue.we.x2c.X2C;
import com.zhangyue.we.x2c.ano.Xml;

import java.util.Calendar;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Demo 启动界面，并跳转HomeActivity
 */
@Xml(layouts = "activity_main")
public class MainActivity extends AppCompatActivity implements View.OnClickListener, OnFeedShowCallBack {

    private long mStartFrameTime = 0;
    private int mFrameCount = 0;
    private static final long MONITOR_INTERVAL = 160L; //单次计算FPS使用160毫秒
    private static final long MONITOR_INTERVAL_NANOS = MONITOR_INTERVAL * 1000L * 1000L;
    private static final long MAX_INTERVAL = 1000L; //设置计算fps的单位时间间隔1000ms,即fps/s;


    public static void start(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 优雅获取任意控件耗时
        // getWidegtCreateTime();
        super.onCreate(savedInstanceState);
        // initView();
        // initThreadPool();

        // getNetStats(getTimesMonthmorning(), System.currentTimeMillis());
        // registerActivityLifecycle();
        // 开启定时任务
        // scheduledTask();

        // 获取FPS
        // getFPS();

        // 替换 setContentView
        // replaceSetContentView();
        X2C.setContentView(MainActivity.this, R.layout.activity_main);

        setTheme(R.style.AppTheme);
    }

    private void replaceSetContentView() {
        new AsyncLayoutInflater(MainActivity.this).inflate(R.layout.activity_main, null, new AsyncLayoutInflater.OnInflateFinishedListener() {
            @Override
            public void onInflateFinished(@NonNull View view, int i, @Nullable ViewGroup viewGroup) {
                setContentView(view);
            }
        });
    }

    private void getWidegtCreateTime() {
        LayoutInflaterCompat.setFactory2(getLayoutInflater(), new LayoutInflater.Factory2() {
            @Override
            public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {

                if (TextUtils.equals(name, "TextView")) {
                    // todo 生成自定义TextView
                }
                // 获取控件创建耗时
                long time = System.currentTimeMillis();
                View view = getDelegate().createView(parent, name, context, attrs);
                LogUtils.i(name + " cost " + (System.currentTimeMillis() - time));
                return view;
            }

            @Override
            public View onCreateView(String name, Context context, AttributeSet attrs) {
                return null;
            }
        });
    }

    private void registerActivityLifecycle() {
        getApplication().registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {

            }

            @Override
            public void onActivityStarted(@NonNull Activity activity) {

            }

            // 在前台
            @Override
            public void onActivityResumed(@NonNull Activity activity) {

            }

            // 退到后台
            @Override
            public void onActivityPaused(@NonNull Activity activity) {

            }

            @Override
            public void onActivityStopped(@NonNull Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(@NonNull Activity activity) {

            }
        });
    }

    private void scheduledTask() {
        Executors.newScheduledThreadPool(1).schedule(new Runnable() {
            @Override
            public void run() {
                // 30 秒消耗流量
                long netUse = getNetStats(System.currentTimeMillis() - 30 * 1000, System.currentTimeMillis());
                // 前台 还是后台
            }
        }, 30, TimeUnit.SECONDS);
    }

    private void initThreadPool() {
        ThreadPoolUtils.getService().execute(new Runnable() {
            @Override
            public void run() {
                // 修改线程名
                Thread.currentThread().setName("New Name");
                // 修改线程优先级
                Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
                LogUtils.i("MainActivity 线程池: " + getTimesMonthmorning());
            }
        });
    }

    private void initView() {
        setContentView(R.layout.activity_main);
    }

    @Override
    public void onClick(View v) {
        /*switch (v.getId()) {
            case R.id.aqie:
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, HomeActivity.class);
                startActivity(intent);
                break;
        }*/
    }

    /**
     * 获取网络数据
     */
    private long getNetStats(long start, long end) {
        // 小于 API 23
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return 0;
        }
        long netDataReceive = 0;        // 接收流量
        long netDataSend = 0;           // 发送流量
        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    Activity#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for Activity#requestPermissions for more details.
            return 0;
        }
        String subId = telephonyManager.getSubscriberId();
        NetworkStatsManager systemService = (NetworkStatsManager)getSystemService(Context.NETWORK_STATS_SERVICE);
        NetworkStats networkStats = null;
        NetworkStats.Bucket bucket = new NetworkStats.Bucket();
        try {
            networkStats = systemService.querySummary(NetworkCapabilities.TRANSPORT_WIFI, subId, start, end);

        } catch (RemoteException e) {
            e.printStackTrace();
        }
        while(networkStats.hasNextBucket()){
            networkStats.getNextBucket(bucket);
            // 判断是否是本App 消耗
            int uid = bucket.getUid();
            if(getUidByPacketName() == uid){
                netDataReceive += bucket.getRxBytes();
                netDataSend += bucket.getTxBytes();
            }
        }

        LogUtils.i("netDataReceive: "+netDataReceive + " netDataSend:"+ netDataSend);
        return netDataReceive + netDataSend;
    }

    private int getUidByPacketName() {
        int uid = -1;
        PackageManager packageManager = MainActivity.this.getPackageManager();
        PackageInfo packageInfo = null;
        try {
            packageInfo = packageManager.getPackageInfo("com.aqielife.aqiemusic", PackageManager.GET_ACTIVITIES);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        uid = packageInfo.applicationInfo.uid;
        Log.i(MainActivity.class.getSimpleName(),packageInfo.packageName);
        return uid;
    }

    private static int getTimesMonthmorning(){
        Calendar cal = Calendar.getInstance();
        cal.set(cal.get(Calendar.YEAR),cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0,0);
        cal.set(Calendar.DAY_OF_MONTH,cal.getActualMinimum(Calendar.DAY_OF_MONTH));
        return (int) (cal.getTimeInMillis());
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void getFPS() {
        // 确保API 版本 > 16
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
            return;
        }
        Choreographer.getInstance().postFrameCallback(new Choreographer.FrameCallback() {
            @Override
            public void doFrame(long frameTimeNanos) {
                if (mStartFrameTime == 0) {
                    mStartFrameTime = frameTimeNanos;
                }
                long interval = frameTimeNanos - mStartFrameTime;
                if (interval > MONITOR_INTERVAL_NANOS) {
                    double fps = (((double) (mFrameCount * 1000L * 1000L)) / interval) * MAX_INTERVAL;
                    mFrameCount = 0;
                    mStartFrameTime = 0;
                } else {
                    ++mFrameCount;
                }

                Choreographer.getInstance().postFrameCallback(this);
            }
        });
    }

    @Override
    public void onFeedShow() {
        DelayInitDispatcher delayInitDispatcher = new DelayInitDispatcher();
        delayInitDispatcher.addTask(new DelayInitTaskA())
                .addTask(new DelayInitTaskB())
                .start();
    }
}
